import axios from 'axios'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // api的base_url
  timeout: 5000, // 请求超时时间
  withCredentials: true // 允许携带凭证
})

// request拦截器
service.interceptors.request.use(
  config => {
    // Do something before request is sent
    
    if (localStorage.getItem('token')) {
      // 去除token前后可能存在的空格
      const token = localStorage.getItem('token').trim();
      config.headers['Authorization'] = token; // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
      config.headers['Content-Type'] = 'application/json';
    }
    console.log('token ', config)
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

import router from '../router'

// respone拦截器
service.interceptors.response.use(
  response => response,
  error => {
    console.log('err' + error) // for debug
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      router.push('/login')
    }
    return Promise.reject(error)
  }
)

export default service